package com.jzo2o.foundations.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author asus
 */
@Service
@RequiredArgsConstructor
public class IServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    private final ServeItemMapper serveItemMapper;


    private final RegionMapper regionMapper;

    @Override
    @Transactional
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        // 调用mapper查询数据，这里由于继承了ServiceImpl<ServeMapper, Serve>，使用baseMapper相当于使用ServeMapper
        PageResult<ServeResDTO> serveResDTOPageResult = PageHelperUtils.selectPage(servePageQueryReqDTO, () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
        return serveResDTOPageResult;
    }

    @Override
    @Transactional
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        if (CollectionUtils.isEmpty(serveUpsertReqDTOList)) {
            return;
        }

        // 提取所有服务项ID和区域ID
        Set<Long> serveItemIds = serveUpsertReqDTOList.stream()
                .map(ServeUpsertReqDTO::getServeItemId)
                .collect(Collectors.toSet());
        Set<Long> regionIds = serveUpsertReqDTOList.stream()
                .map(ServeUpsertReqDTO::getRegionId)
                .collect(Collectors.toSet());

        // 批量查询服务项和服务区域
        List<ServeItem> serveItems = serveItemMapper.selectBatchIds(serveItemIds);
        Map<Long, ServeItem> serveItemMap = serveItems.stream()
                .filter(item -> item.getActiveStatus() == FoundationStatusEnum.ENABLE.getStatus())
                .collect(Collectors.toMap(ServeItem::getId, item -> item));

        List<Region> regions = regionMapper.selectBatchIds(regionIds);
        Map<Long, Region> regionMap = regions.stream()
                .collect(Collectors.toMap(Region::getId, region -> region));

        // 验证服务项是否存在且已启用
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            ServeItem serveItem = serveItemMap.get(serveUpsertReqDTO.getServeItemId());
            if (serveItem == null) {
                throw new ForbiddenOperationException("服务项不存在或未启用");
            }
        }

        // 验证区域是否存在
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            Region region = regionMap.get(serveUpsertReqDTO.getRegionId());
            if (region == null) {
                throw new ForbiddenOperationException("区域尚未开通");
            }
        }

        // 检查是否已经添加过
        List<Serve> existingServes = baseMapper.selectList(Wrappers.<Serve>lambdaQuery()
                .in(Serve::getRegionId, regionIds)
                .in(Serve::getServeItemId, serveItemIds));
        Set<String> existingServeKeys = existingServes.stream()
                .map(s -> s.getRegionId() + "_" + s.getServeItemId())
                .collect(Collectors.toSet());

        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            String key = serveUpsertReqDTO.getRegionId() + "_" + serveUpsertReqDTO.getServeItemId();
            if (existingServeKeys.contains(key)) {
                throw new ForbiddenOperationException("服务项不能重复添加");
            }
        }

        // 批量插入数据
        List<Serve> serveList = serveUpsertReqDTOList.stream()
                .map(req -> Serve.builder()
                        .regionId(req.getRegionId())
                        .serveItemId(req.getServeItemId())
                        .cityCode(regionMap.get(req.getRegionId()).getCityCode())
                        .price(req.getPrice())
                        .build())
                .collect(Collectors.toList());

        saveBatch(serveList);
    }

    @Override
    public Serve update(Long id, BigDecimal price) {
        // 更新服务价格
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getPrice, price)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("更新服务价格失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    @Transactional
    @CachePut(value = RedisConstants.CacheName.SERVE,key = "#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    public void onSale(Long id) {
        //1、当前区域服务(serve)必须是草稿或者下架状态
        Serve serve = getById(id);
        if(serve==null || (serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("当前服务启用失败！");
        }

        //2、该服务对应的服务项(serve_item)必须是启用状态
        ServeItem serveItem = serveItemMapper.selectOne(Wrappers.<ServeItem>lambdaQuery().eq(ServeItem::getId, serve.getServeItemId()));
        if(serveItem==null || serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("当前服务项状态不正确！");
        }

        //3、上架操作
        boolean update = lambdaUpdate()
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .eq(Serve::getId,id)
                .update();
        if(!update){
            throw new ForbiddenOperationException("服务上架失败！");
        }
    }

    @Override
    public void delete(Long id) {
        // 区域服务必须是草稿才能删除
        boolean remove = remove(Wrappers.<Serve>lambdaQuery().eq(Serve::getId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.INIT.getStatus()));
        if (!remove) {
            throw new ForbiddenOperationException("区域服务必须是草稿才能删除");
        }
        baseMapper.deleteById(id);
    }

    @Override
    @Transactional
    @CacheEvict(value = RedisConstants.CacheName.SERVE, key = "#id")
    public void offSale(Long id) {
        // 区域服务必须是上架才能下架
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("区域服务必须是上架才能下架");
        }
        baseMapper.updateById(baseMapper.selectById(id));
    }

    @Override
    public void setHot(Long id) {
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, 1)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("设置服务项热门失败");
        }
        baseMapper.updateById(baseMapper.selectById(id));
    }

    @Override
    public void offHot(Long id) {
        boolean update = lambdaUpdate().eq(Serve::getId, id)
                .set(Serve::getIsHot, 0)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("取消服务项热门失败");
        }
        baseMapper.updateById(baseMapper.selectById(id));
    }

    @Override
    public Long serveOnSaleNumber(Long id) {
        Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getServeItemId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
        );
        return count;
    }

    @Override
    //    @Cacheable(value = "JZ_CACHE:SERVE_RECORD",key = "#id")
    @Cacheable(value = RedisConstants.CacheName.SERVE,key = "#id")
    public Serve queryServeByIdCache(Long id) {
        return getById(id);
    }


    @Override
    public Long serveOnSaleCount(Long id) {
        Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getRegionId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
        );
        return count;
    }


}




